package beautiful.butterfly.drds.binlog.netty.server;


import beautiful.butterfly.drds.binlog.connection.Connection;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.channels.SocketChannel;
import java.util.List;

@Slf4j
public class MyNioServerSocketChannel extends NioServerSocketChannel
{


    // 继承已经有的类，用于干预连接
    @Override
    protected int doReadMessages(List<Object> buf) throws Exception
    {
        // logger.debug("\ndoReadMessages(...) enter....\n触发了新的连接...开始准备2阶段提取");
        // logger.debug("buf :" + buf);
        // LoggerUtils.debug(logger, new Exception().toString());
        // 原始部分,直接关闭
        try
        {
            SocketChannel tempCh = javaChannel().accept();
            tempCh.close();
        } catch (Exception e)
        {

        }

        // 移花接木
        Connection connection = NettyQueue.getObject();
        try
        {
            if (connection != null)
            {
                NioSocketChannelExtend nioSocketChannelExtend = new NioSocketChannelExtend(this, connection.getSocketChannel(),
                        connection.getConnectionAttributes());
                buf.add(nioSocketChannelExtend);
                log.info("databaseName conn is as follows: " + connection.getSocketChannel());
                // logger.debug("buf :" + buf);
                // 成功了，这下可以放心了
                connection.getConnectionAttributes().setNettyManageState(1);// 成功了
                return 1;
            }
        } catch (Throwable t)
        {
            log.info("Failed to create a new channel from an accepted socket." + t);
            try
            {
                connection.close();
            } catch (Throwable t2)
            {
                log.info("Failed to close a socket." + t2);
            }
            //设置失败
            connection.getConnectionAttributes().setNettyManageState(-1);// 失败了
        }
        return 0;

    }
}
